package com.pzr.soccer.crawlerHelper;

import com.pzr.soccer.consts.GeneralConst;
import com.ruiyun.jvppeteer.core.Puppeteer;
import com.ruiyun.jvppeteer.core.browser.Browser;
import com.ruiyun.jvppeteer.core.browser.BrowserFetcher;
import com.ruiyun.jvppeteer.core.page.Page;
import com.ruiyun.jvppeteer.options.LaunchOptions;
import com.ruiyun.jvppeteer.options.LaunchOptionsBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;


public class JvppeteerHelper {

    private static Browser browser;

    static {
        try {
            BrowserFetcher.downloadIfNotExist(null);
        } catch (InterruptedException | ExecutionException | IOException e) {
            e.printStackTrace();
        }

        ArrayList<String> argList = new ArrayList<>();
        LaunchOptions options = new LaunchOptionsBuilder().withArgs(argList).withHeadless(true).build();
        options.setTimeout(10 * 1000);
        options.setIgnoreHTTPSErrors(true);
        argList.add("--no-sandbox");
        argList.add("--disable-setuid-sandbox");
        try {
            browser = Puppeteer.launch(options);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static String getContent(String url) {
        Page page = null;
        String body = "";
        try {
            page = browser.newPage();
            page.goTo(url);
            body = page.content();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            body = GeneralConst.Parse_Errors_Occurred + e.getMessage();
        }

        try {
            if (page != null) {
                page.close();
            }

        } catch (Exception e) {
            System.out.println("page close error:" + e.getMessage());
        }

        return body;
    }


    public static void closeBrowser() {
        browser.close();
    }

}
